<template>
  <div class="wrapper-echarts">
    <!-- <div ref="dom" class="charts" :style="{ width: width, height: height }"></div> -->
    <!-- <div ref="dom" class="charts" style="width: 100%; height: 100%"></div> -->
    <div id="domId" :style="{ width: width, height: height }"></div>
  </div>
</template>

<script>
import * as echarts from 'echarts/core'
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components'
import { LineChart } from 'echarts/charts'
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([TitleComponent, TooltipComponent, LegendComponent, GridComponent, LineChart, CanvasRenderer])

import { defineComponent, onMounted, onBeforeUnmount, watch, shallowRef } from 'vue'

export default defineComponent({
  name: 'EChartsViewCom',
  props: {
    option: {
      type: Object,
      default: () => {
        return {}
      },
    },
    width: { type: String, default: '100%' },
    height: { type: String, default: '600px' },
  },
  setup(props) {
    // 使用 shallowRef 进行保存
    // 详情： https://cn.vuejs.org/api/reactivity-advanced.html#shallowref
    const chart = shallowRef(null)

    // 绘制 echart
    const drawChart = (option) => {
      if (!chart.value) {
        chart.value = echarts.init(document.getElementById('domId'))
      } else {
        // notMerge 可选。是否不跟之前设置的 option 进行合并，默认为 false，即表示合并
        // 如果为 true，表示所有组件都会被删除，然后根据新 option 创建所有新组件
        chart.value.setOption(option, true)
        // echarts 图表自适应
        window.addEventListener('resize', () => {
          chart.value.resize()
        })
      }
    }

    watch(
      () => props.option,
      (value) => {
        // console.log('watch value:', value)
        drawChart(value)
      },
      { deep: true }
    )

    onMounted(() => {
      window.onresize = function () {
        if (chart.value) {
          chart.value.resize()
        }
      }
    })

    onBeforeUnmount(() => {
      if (chart.value) {
        chart.value.dispose()
        chart.value = null
      }
    })

    return {
      chart,
      drawChart,
    }
  },
})
</script>

<style lang="scss" scoped></style>
